package com.changyue.activity.mainTab;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentTabHost;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.WindowManager;
import android.widget.TabHost.TabSpec;
import android.widget.TextView;

import com.changyue.bleHelper.ScanActivity;
import com.changyue.blood.R;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

public class MainTabActivity extends FragmentActivity {

    private static String TAG = "MainTabActivity";

    private FragmentTabHost mTabHost;

    private LayoutInflater layoutInflater;

    public static List<String> mDetectionName = null;

    //	private Class fragmentArray[] = {FragmentDevice.class};
    private Class fragmentArray[] = {};

    private int mTextviewArray[] = {R.string.title_device, R.string.detection, R.string.history};

    private boolean isShowTestView = false;

    public void onCreate(Bundle savedInstanceState) {
        try {
            ViewConfiguration config = ViewConfiguration.get(this);
            @SuppressLint("SoonBlockedPrivateApi")
            Field menuKeyField = ViewConfiguration.class.getDeclaredField("sHasPermanentMenuKey");

            if (menuKeyField != null) {
                menuKeyField.setAccessible(true);
                menuKeyField.setBoolean(config, false);
            }
        } catch (Exception ex) {
            // Ignore
        }
        super.onCreate(savedInstanceState);

        setContentView(R.layout.main_tab_layout);

        ActionBar ab = getActionBar();
        ab.setHomeButtonEnabled(true);

        mDetectionName = new ArrayList<>();
        mDetectionName.add(getString(R.string.pesticide_detection));

        initView();
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        if (checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED ||
                checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED ||
                checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED ||
                checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            // Permission is not granted
            requestPermissions(new String[]{
                    Manifest.permission.ACCESS_COARSE_LOCATION,
                    Manifest.permission.ACCESS_FINE_LOCATION,
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0);
            return;
        }

        EventBus.getDefault().register(this);
    }


    @Subscribe
    public void onEventMainThread(String event) {
        if (event != null && event.equals(ScanActivity.class.getName())) {
            isShowTestView = true;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (isShowTestView) {
            isShowTestView = false;
            mTabHost.setCurrentTab(1);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    }

    private void initView() {
        layoutInflater = LayoutInflater.from(this);

        mTabHost = (FragmentTabHost) findViewById(android.R.id.tabhost);
        mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);

        int count = fragmentArray.length;

        for (int i = 0; i < count; i++) {
            TabSpec tabSpec = mTabHost.newTabSpec(getString(mTextviewArray[i])).setIndicator(getTabItemView(i));
            mTabHost.addTab(tabSpec, fragmentArray[i], null);
            mTabHost.getTabWidget().getChildAt(i).setBackgroundResource(R.drawable.selector_tab_background);
        }
    }

    private View getTabItemView(int index) {
        View view = layoutInflater.inflate(R.layout.tab_item_view, null);

//		ImageView imageView = (ImageView) view.findViewById(R.id.imageview);
//		imageView.setImageResource(mImageViewArray[index]);

        TextView textView = (TextView) view.findViewById(R.id.textview);
        textView.setText(mTextviewArray[index]);
        textView.setTextColor(getResources().getColor(R.color.dark_gray));

        return view;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
//		FragmentManager fragmentManager = getSupportFragmentManager();
//		for (int indext = 0; indext < fragmentManager.getFragments().size(); indext++) {
//			Fragment fragment = fragmentManager.getFragments().get(indext); //�ҵ���һ��Fragment
//			if (fragment == null) {
//				Log.w(TAG, "Activity result no fragment exists for index: 0x"
//						+ Integer.toHexString(requestCode));
//			}
//			else {
//				handleResult(fragment, requestCode, resultCode, data);
//			}
//		}
    }

    /**
     * @param fragment
     * @param requestCode
     * @param resultCode
     * @param data
     */
    private void handleResult(Fragment fragment, int requestCode, int resultCode, Intent data) {
        fragment.onActivityResult(requestCode, resultCode, data);
        Log.e("xxx", "Fragment" + fragment.getClass().getName());
        List<Fragment> childFragment = fragment.getChildFragmentManager().getFragments(); //�ҵ��ڶ���Fragment
        if (childFragment != null)
            for (Fragment f : childFragment)
                if (f != null) {
                    handleResult(f, requestCode, resultCode, data);
                }
    }
}
